from django.db import models
import inspect
from decimal import *
from django.db.models import DecimalField

def safe(value, default):
	if value:
		return value
	else:
		return default


def sum_values(iter, start = 0):
	total = start
	for i in iter:
		try:
			v = i
		except:
			v = 0
		if v:
			total += v
	return total
	
def sum_inline(self, inline, field,start = 0):
	inline = getattr(self, inline)
	return sum_values([getattr(i, field)  for i in  inline.all()])
	

class ExtraModel(models.Model):

	def __init__(self, *args, **kwargs):
		super(ExtraModel, self).__init__(*args, **kwargs)
		self.defaults = []
		for c in dir(self):
			if c[:8] == "default_":
				if hasattr(self, c[8:]):
					self.defaults.append(c[8:])
		self.gets = []
		for c in dir(self):
			if c[:4] == "get_":
				if hasattr(self, c[4:]):
					self.gets.append(c[4:])

	def save(self, *args, **kwargs):
		self.set_defaults()
		super(ExtraModel, self).save(*args, **kwargs)
		if self.set_gets():
			super(ExtraModel, self).save(*args, **kwargs)
	
	def set_defaults(self):
		cambio = False
		for a in self.defaults:
			if  not  getattr(self, a):
				v = eval("self.default_%s()" % a)
				self.__setattr__(a, v)
				cambio = True
		return cambio
	

	def set_gets(self):
		cambio = False
		for a in self.gets:
			if True:
				v = eval("self.get_%s()" % a)
				c = self.__class__
				if isinstance(self._meta.get_field_by_name(a)[0], DecimalField):
					if v:
						v =  Decimal(str(v))
				if getattr(self, a) <> v:
					cambio = True
				setattr(self,a, v)
		return cambio


	class Meta:
		abstract = True


#def calc(sender, instance, created, **kwargs):
#	pass
	
#from django.db.models import signals
#signals.post_save.connect(calc, sender=None)
